package com.dorukdestan.p2pshare.network;

import java.net.InetAddress;
import java.util.ArrayList;

import com.dorukdestan.p2pshare.logger.Logger;
import com.dorukdestan.p2pshare.model.DownloadingFile;
import com.dorukdestan.p2pshare.model.SearchResult;
import com.dorukdestan.p2pshare.storage.SearchResults;

public class DownloadProcess implements Runnable{

	private DownloadingFile downloadingFile;
	private Logger logger;
	
	public DownloadProcess(DownloadingFile downloadingFile) {
		this.downloadingFile = downloadingFile;
		logger = new Logger(getClass());
	}

	@Override
	public void run() {
		String fileHash = downloadingFile.getExpectedHashValue();
		long fileLength = downloadingFile.getExpectedLength();
		long index = 0;
		
		// split file into chunks
		SearchResult searchResult = SearchResults.getSearchResults().get(downloadingFile.getExpectedHashValue());
		
		if(searchResult == null){
			logger.error("FATAL: searchresult return null for hash " + fileHash);
			return;
		}
		
		int numberOfPeers = searchResult.getPeerAddresses().size();
		ArrayList<InetAddress> peerAddresses = searchResult.getPeerAddresses();
		
//		int totalNumberOfChunks = (int) (fileLength / Constants.FILE_CHUNK_SIZE);
//		if(fileLength % Constants.FILE_CHUNK_SIZE != 0){
//			++totalNumberOfChunks;
//		}
		
		for (int i = 0; i < numberOfPeers; i++) {
			
		}
		
//		int numberOfChunksFromEachPeer = totalNumberOfChunks / numberOfPeers;
//		if(totalNumberOfChunks % numberOfPeers != 0){
//			++numberOfChunksFromEachPeer;
//		}
		
		logger.debug("\nfileLength " + fileLength + "\n" +
					"numberOfPeers " + numberOfPeers+ "\n" );
		
		long intervalPerPeer = fileLength / numberOfPeers;
		long endIndex;
		
		for (InetAddress peerAddress : peerAddresses) {
			// request chunks from every peer
			endIndex = index + intervalPerPeer;
			
			FileTransferOperations.requestFileChunk(fileHash, index, (endIndex > fileLength? fileLength : endIndex), peerAddress);

			index = endIndex + 1;
		}
		
		logger.debug("index="+index + " | " + "length="+ fileLength);
		
		/**
		 *  Note that handling responses from peers is done in FileTransferQueryServer.
		 *  So we are done here at this point
		 */
	}
	
}
